<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
  <title>上传文件</title>
  <link rel="stylesheet" type="text/css" href="./index.css">
</head>

<body>
  <div class="box">
    <button class="btn">上传</button>
    <input class="input-file" type="file" name="files" id="file" multiple>
    <!-- 文件 -->
    <div class="fileList" id="fileList"></div>
    <!-- 备注 -->
		<textarea class="textarea" :rows="4" placeholder="备注信息" id="remarkValue"> </textarea>
    <!-- 检查人 -->
    <div id="selector" style="display: none">
        <span class="mr-selector">请选择选项</span>
        <span class="arrow"></span>
        <ul class="select" id="select">
        </ul>
    </div>
    <!-- 提交 -->
    <div class="submit">
      <!-- 输入文档提交 -->
      <button class="btn btn1" onclick="UploadWebview.inputSubmit()" id="inputSubmit" style="display: none">提交</button>
      <!-- 输出文档提交 -->
      <button class="btn btn1" onclick="UploadWebview.outputSubmit()" id="outputSubmit" style="display: none">提交</button>
    </div>
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

  <script>
    // 用到的api
    const apis = {
      user: '/gateway/tall/v1.0/users/userId',
      file: {
        m: '/filedeal/file/upload/multiple',
        s: '/filedeal/file/upload/single',
      },
      uploadForDoc: '/gateway/tall/v1.0/inputDoc/uploadForDoc',
      uploadDelivers: '/gateway/tall/v1.0/delivers',
      allRole: '/gateway/tall/v1.0/roles/query/allRole',
    };

    const UploadWebview = {
      domain: '', // 域
      userId: '', // 用户id
      type: 'm', // 文件上传类型 m->多文件上传 s->单文件上传
      token: '',
      lists: [],
      api: {
        user: '',
        file: '',
        uploadForDoc: '',
        uploadDelivers: '',
        allRole: '',
      },
      docId : '',
      projectId: '',
      taskId: '',
      rolesList: [],
      showRoles: 'false',
      fileInfo: [],

      // 初始化
      init() {
        const query = util.parseUrl(location.search);
        if (!util.validateQuery(query)) return; // 缺少参数 return

        let { u, t, d, docId, projectId, taskId, show } = query;
        this.type = t || 'm';
        this.domain = d || 'www.tall.wiki';
        this.docId = docId;
        this.projectId = projectId;
        this.taskId = taskId;
        this.showRoles = show;
        // 判断上传输入文档还是输出文档，需不需要选择检查人
        if(show === 'true'){
          $("#selector").show()
          $("#outputSubmit").show()
        }else{
          $("#inputSubmit").show()
        }

        this.api.user = `//${this.domain}${apis.user}`;
        this.api.file = `//${this.domain}${apis.file[this.type]}`;
        this.api.uploadForDoc = `//${this.domain}${apis.uploadForDoc}`;
        this.api.uploadDelivers = `//${this.domain}${apis.uploadDelivers}`;
        this.api.allRole = `//${this.domain}${apis.allRole}`;

        this.getTokenByUserId(u);

        const fileElement = document.getElementById('file');
        fileElement.addEventListener('change', function(event) {
          const files = event.target.files;
          const formData = new FormData();
          Array.prototype.forEach.call(files,item => {
            formData.append('files', item);
          });
          UploadWebview.upload(formData)
        }, false);
      },

      /**
        * 通过userId获取token
        * @param {string} userId 用户id
        */
      getTokenByUserId(userId) {
        return axios.get(this.api.user, { params: { userId } })
          .then(res => {
            const { msg, data, code } =res.data;
            if (code === 200) {
              this.token = data.token;
              // 发送获取token成功的消息
              util.postMsg({ type: 'user', msg: '获取token成功', ok: 1 });
              if(this.showRoles === 'true'){
                // $('#selector').css('display') = 'block';
                // console.log('display',$('#selector').css)

                this.getAllRoles()
              }
            } else {
              throw msg;
            }
          })
          .catch(err => {
            console.warn(err);
            // 发送获取token失败的消息
            util.postMsg({ type: 'user', msg: err, ok: 0 });
          })
      },

      // 上传文件
      upload(formData) {
        util.postMsg({ type: 'beforeUpload' }); // 开始上传的消息
        axios.post(this.api.file, formData, {
          headers: {
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(res => {
          util.postMsg({ type: 'afterUpload' }); // 结束上传的消息
          const { msg, data, code } = res.data;
          if (code === 200) {
            util.postMsg({ type: 'file', msg: '上传成功', data, ok: 1 }); // 上传成功的消息
            this.fileInfo = data;
            this.lists = data.map(item => item.id);
            let str = '';
            for (let i = 0; i < data.length; i++) {
              const item = data[i];
              str += `
                <ul>
                  <li>${item.name}</li>
                </ul>
                `
            }
            $('#fileList').html(str);
          } else {
            throw msg;
          }
        })
        .catch(err => {
          util.postMsg({ type: 'afterUpload' }); // 结束上传的消息
          console.warn(err);
          util.postMsg({ type: 'file', msg: err, ok: 0 }); // 上传失败的消息
        })
      },

      /**
       * 输入文档提交
       * @param {Array} docId 文档Id
       * @param {Array} fileIds 文档
       * @param {string} remark 备注信息
       */
      inputSubmit(){
          let remark=document.getElementById('remarkValue').value;
          let params = { param: { docId: this.docId, fileIds: this.lists, remark } }
          axios.post(this.api.uploadForDoc, params, {
            headers: {
              'Authorization': `Bearer ${this.token}`,
              'Content-Type': 'application/json;charset=UTF-8'
            }
          })
          .then(res => {
            const { msg, data, code } =res.data;
            if (code === 200) {
              // 发送获取token成功的消息
              util.postMsg({ type: 'user', msg: '提交成功', ok: 1 });
            } else {
              throw msg;
            }
          })
          .catch(err => {
            console.warn(err);
            util.postMsg({ type: 'file', msg: err, ok: 0 }); // 上传失败的消息
          })
        },

        /**
       * 输出文档提交
       * @param {string} deliverId 文档Id
       * @param {Array} checkerIdList 检查人
       * @param {Array} fileIds 文档
       * @param {string} description 备注信息
       * @param {string} taskId 任务id
       */
      outputSubmit(){
          let remark=document.getElementById('remarkValue').value;
          let params = { checkerIdList: this.rolesList, deliverId: this.docId, description: remark, fileInfo: this.fileInfo,taskId: this.taskId }
          axios.post(this.api.uploadDelivers, params, {
            headers: {
              'Authorization': `Bearer ${this.token}`,
              'Content-Type': 'application/json;charset=UTF-8'
            }
          })
          .then(res => {
            const { msg, data, code } =res.data;
            if (code === 200) {
              // 发送获取token成功的消息
              util.postMsg({ type: 'user', msg: '提交成功', ok: 1 });
            } else {
              throw msg;
            }
          })
          .catch(err => {
            console.warn(err);
            util.postMsg({ type: 'file', msg: err, ok: 0 }); // 上传失败的消息
          })
        },

      /**
       * 获取所有角色
       * @param {Array} docId 文档Id
       * @param {Array} fileIds 文档
       * @param {string} remark 备注信息
       */
      getAllRoles(){
          let params = { projectId: this.projectId }
          axios.post(this.api.allRole, params, {
            headers: {
              'Authorization': `Bearer ${this.token}`,
              'Content-Type': 'application/json;charset=UTF-8'
            }
          })
          .then(res => {
            const { msg, data, code } =res.data;
            if (code === 200) {
              // 发送获取token成功的消息
              // util.postMsg({ type: 'user', msg: '提交成功', ok: 1 });
                let str = '';
                for (let i = 0; i < data.length; i++) {
                  const item = data[i];
                  str += `
                      <li value="${item.roleId}">${item.roleName}</li>
                    `
                }
                $('#select').html(str);
                this.setSelectValue(data,this.rolesList)
            } else {
              throw msg;
            }
          })
          .catch(err => {
            console.warn(err);
            util.postMsg({ type: 'file', msg: err, ok: 0 }); // 上传失败的消息
          })
        },

      // 选择角色
        setSelectValue(roles,rolesList){
            var selector = $("#selector");
            var select = $("#selector .select");  //模拟select的ul选项
            var mrSelector = $("#selector .mr-selector");
            var li = $("#selector .select li"); //li选项

            selector.click(function(eve){
                eve.stopPropagation();   //阻止冒泡避免点击后消失
            });
            mrSelector.click(function(){
                select.toggle();
            });
            li.click(function(eve){
            	var ttt = $(mrSelector).text();
              var index = $(this).index();
              var text = ttt+$(this).text();
              mrSelector.text(text);
              if(li[index].getAttribute('class') === 'active') {
                li[index].classList.remove('active')
                var text = ttt.replace($(this).text(),'');
                mrSelector.text(text);
                for(let i=0;i<rolesList.length;i++){
                  if(rolesList[i] === roles[index].roleId){
                    rolesList.splice(i,1)
                    break
                  }
                }
              } else {
                li[index].classList.add('active')
                var text = ttt+$(this).text();
                mrSelector.text(text);

                rolesList.push(roles[index].roleId)
              }
            });

            $("body").click(function(){
                select.hide();
            });
      }
    }

    const util = {
      /**
       * window.postMessage 发送消息
       * @param {object} data 消息体
       */
      postMsg(data) {
        const msg = JSON.stringify(data);
        // const targetOrigin = this.getParentOrigin() || '*';
        const targetOrigin = '*';
        window.postMessage(msg, targetOrigin);
      },

      // 获取父容器的
      getParentOrigin() {
        let url = '';
        if (parent !== window) {
          try {
            url = parent.location.href;
          } catch (error) {
            url = document.referrer;
          }
        };
        return url;
      },

      // 将location.search解构为对象
      parseUrl() {
        const search = location.search;
        if (!search) return null;
        let result = {};
        const qs = search.slice(1);

        // 如果只有一个参数
        if (qs.indexOf('&') === -1) {
          const arr = qs.split('=');
          result[arr[0]] = arr[1];
        } else {
          // 如果有多个参数 &
          const qsArr = qs.split('&');
          qsArr.forEach(item => {
            const arr = item.split('=');
            result[arr[0]] = arr[1];
          });
        }
        console.table('query:', result)
        return result;
      },

      /**
      * 验证query参数的完整性
      * @param {object | null} query location参数对象
      */
      validateQuery(query) {
        if (!query) {
          // alert('缺少参数信息');
          util.postMsg({ type: 'param', msg: '缺少参数信息', ok: 0 });
          return;
        }
        const { u, t, d } = query;
        if (!u) {
          util.postMsg({ type: 'param_u', msg: '缺少用户id参数 u', ok: 0 });
          return
        }
        return true
      }
    }

    // 初始化
    UploadWebview.init();

  </script>
</body>
</html>
